package com.ruoyi.common.encrypt.config;

import com.ruoyi.common.encrypt.util.SM4Util;
import com.ulisesbocchio.jasyptspringboot.EncryptablePropertyDetector;
import com.ulisesbocchio.jasyptspringboot.EncryptablePropertyResolver;
import com.ulisesbocchio.jasyptspringboot.exception.DecryptionException;

import java.util.Optional;

public class CustomEncryptablePropertyResolver implements EncryptablePropertyResolver {
    private final EncryptablePropertyDetector detector;

    public CustomEncryptablePropertyResolver(EncryptablePropertyDetector detector) {
        this.detector = detector;
    }

    @Override
    public String resolvePropertyValue(String value) {
        return Optional.ofNullable(value).filter(detector::isEncrypted).map(resolvedValue -> {
            try {
                String unwrappedProperty = detector.unwrapEncryptedValue(value);
                return SM4Util.decryptEcb(unwrappedProperty).trim();
            } catch (Exception e) {
                e.printStackTrace();
                throw new DecryptionException("Unable to Decrypt: " + value + ". Decryption of Properties failed, make sure encryption/decryption " + "passwords match", e);
            }
        }).orElse(value);
    }
}
